package com.yonyou.wdt.job;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

@Component
public class YsTaxToRedisJob extends BaseConfig {
    private static Logger logger = LoggerFactory.getLogger(YsTaxToRedisJob.class);
    @Resource
    private YonsuiteService yonsuiteService;
    private static final String JOB_CLASS="longPai004";

    @XxlJob("YsTaxToRedisJob")
    public ReturnT<String> ysTaxToRedisJob() {
        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(JOB_CLASS,dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        try {
            HashMap<String, Object> queryMap = new HashMap<>();
            queryMap.put("pageIndex", 1);
            queryMap.put("pageSize", 500);
            // 税率档案列表查询
            JSONObject outTaxRes = yonsuiteService.ysTaxListQuery(queryMap, dto);
            if ("200".equals(outTaxRes.getStr("code"))) {
                JSONArray recordList = null != outTaxRes.getJSONObject("data") && null != outTaxRes.getJSONObject("data").getJSONArray("recordList") ? outTaxRes.getJSONObject("data").getJSONArray("recordList") : new JSONArray();
                for (Object taxObj : recordList) {
                    JSONObject taxJson = (JSONObject) taxObj;
                    RedisUtils.set(dto.getTenantId() + ":TAX:" + taxJson.getStr("id"), taxJson.getBigDecimal("ntaxrate"));
                }
                InsertLogger(JOB_CLASS,null, "1", "YS税率档案同步Redis缓存任务执行完成，共：{" + recordList.size() + "}条");
                logger.info("YS税率档案同步Redis缓存任务执行完成，共：{}条", recordList.size());
            } else {
                XxlJobHelper.handleFail(outTaxRes.getStr("message"));
                InsertLogger(JOB_CLASS,null, "0", outTaxRes.getStr("message"));
                return ReturnT.FAIL;
            }
        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
            InsertLogger(JOB_CLASS,null, "0", e.getMessage());
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }


}
